package com.pluszg.nutrition.common.bean;

import com.pluszg.nutrition.common.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.File;
import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * 获取spring上下文
 */
@Slf4j
public class ApplicationHolder implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            context = applicationContext;
        }
    }

    /**
     * 获取应用程序的名称
     *
     * @return
     */
    public static String getApplicationName() {
        if (context != null) {
            return context.getEnvironment().getProperty("spring.application.name");
        }
        return null;
    }

    /**
     * 获取系统临时文件目录
     *
     * @return
     */
    public static String getTempPath() {
        String tmpdir = System.getProperty("java.io.tmpdir");
        Assert.notBlank(tmpdir);
        if (tmpdir.endsWith(File.separator)) {
            return tmpdir.substring(0, tmpdir.length() - File.separator.length());
        }
        return tmpdir;
    }

    /**
     * 获取当前环境
     *
     * @return
     */
    public static String[] getActiveProfile() {
        if (context != null) {
            return context.getEnvironment().getActiveProfiles();
        }
        return null;
    }

    public static <T> T getBean(String beanName) {
        if (context != null) {
            try {
                return (T) context.getBean(beanName);
            } catch (Exception e) {
                log.error("Failed to get bean.beanName=[{}],message=[{}]", beanName, e.getMessage());
            }
        }
        return null;
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
        if (context != null) {
            try {
                return context.getBeansWithAnnotation(annotation);
            } catch (Exception e) {
                log.error("Failed to get bean.annotation=[{}],message=[{}]", annotation, e.getMessage());
            }
        }
        return null;
    }

    public static <T> T getBean(Class<T> beanClass) {
        if (context != null) {
            try {
                return context.getBean(beanClass);
            } catch (Exception e) {
                log.error("Failed to get bean.beanClass=[{}],message=[{}]", beanClass, e.getMessage());
            }
        }
        return null;
    }
}
